package proxy.dynamic.jdk;

import proxy.modules.DynamicDataSourceEntry;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Feng
 * @date 2019/3/12 21:30
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    private Object object;

    public Object getInstance(Object target){
        this.object = target;
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);
        Object object = method.invoke(this.object, args);
        after();
        return object;
    }

    private void after() {
        System.out.println("Proxy after");
    }

    private void before(Object arg) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        System.out.println("Proxy before");
        Long time = (Long) arg.getClass().getMethod("getCreatTime").invoke(arg);
        Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
        System.out.println("静态代理类自动分配到【DB_"+ dbRouter +"】数据源处理数据.");
        DynamicDataSourceEntry.set(dbRouter);
    }
}
